package com.jm.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.core.appender.SyslogAppender;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.criteria.internal.expression.function.AggregationFunction.COUNT;

import com.jm.entity.Agenttype;
import com.jm.entity.Area;
import com.jm.entity.Order;
import com.jm.entity.Orderitem;
import com.jm.entity.Product;
import com.jm.entity.ProductAgent;
import com.jm.entity.User;
import com.jm.entity.Userstock;
import com.jm.viewmodel.ViewAgentProductPrice;
import com.jm.viewmodel.ViewArea;
import com.jm.viewmodel.ViewOrder;
import com.jm.viewmodel.ViewProduct;
import com.jm.viewmodel.ViewUserStock;
import com.opensymphony.xwork2.util.logging.log4j2.Log4j2Logger;
import com.jm.viewmodel.ViewOrder.OrderItem;
import com.sun.glass.ui.View;
import com.sun.org.apache.xpath.internal.operations.And;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Collections;

import sun.nio.cs.MS1250;

public class AgentDao {
		
		/***
		 *根据用户id查询产品信息，包括产品对应的各级代理价格
		 * @param uid
		 * @return
		 */
		public List<ViewAgentProductPrice> getProductByAgentId(long uid){
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();
			String hql = "from com.jm.entity.User u where userid=:uid";
			@SuppressWarnings("unchecked")
			List<User>users = mSession.createQuery(hql).setParameter("uid", uid).list();
			
			if(users.size()>0){
				List<ViewAgentProductPrice> viewAgentProductPrices = new ArrayList<>();
				for(User u : users){
					Agenttype agenttype = u.getAgenttype();
					if(agenttype!=null){
						Set<ProductAgent>productAgents = agenttype.getProductAgents();
						if (productAgents!=null && productAgents.size()>0){
							for(ProductAgent pa : productAgents){
								Product product = pa.getProduct();
								if (product!=null){
									ViewAgentProductPrice viewAgentProductPrice = new ViewAgentProductPrice();
									viewAgentProductPrice.setPname(product.getPname());
									viewAgentProductPrice.setCost(String.valueOf(pa.getCost()));
									viewAgentProductPrice.setPdescribe(product.getPdescribe());
									viewAgentProductPrice.setProducticon(product.getPicurl());
									viewAgentProductPrice.setPid(product.getPid());
									viewAgentProductPrices.add(viewAgentProductPrice);
								}
							}
						}
					}
				}
				mSession.close();
//				mSessionFactory.close();
				
				return viewAgentProductPrices;
			}else{
				mSession.close();
//				mSessionFactory.close();
				return null;
			}
			
		}

		public List<ViewUserStock> getUserStockByUid(long uid){
			List<ViewUserStock>viewUserStocks = new ArrayList<>();
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();		
			String hql = "from com.jm.entity.User u where u.userid =:uid";
			@SuppressWarnings("rawtypes")
			List users =  mSession.createQuery(hql).setParameter("uid", uid).list();
			User user = null;
			if(users.size()>0){
				user = (User) users.get(0);
			}
			if (user !=null){
				Set<Userstock> userstock = user.getUserstocks();
				if(userstock!=null && userstock.size()>0){
					for(Userstock us:userstock){						
						if (us.getProduct()!=null){
							ViewUserStock viewUserStock = new ViewUserStock();
							viewUserStock.setPid(us.getProduct().getPid());
							viewUserStock.setPdescribe(us.getProduct().getPdescribe());
							viewUserStock.setPicurl(us.getProduct().getPicurl());
							viewUserStock.setPname(us.getProduct().getPname());
							viewUserStock.setTotalstock(us.getTotalstock());
							viewUserStocks.add(viewUserStock);
						}
					}
				}
			}
			mSession.close();
//			mSessionFactory.close();
			return viewUserStocks;
			
		}
		
		
		/***
		 * 下订单
		 * 总代 600桶
		 * @param viewOrder
		 * @return
		 */
		public Long addUsrOrder(ViewOrder viewOrder){
			
			Long count = 0L;
			if(viewOrder!=null && viewOrder.getOrderItems()!=null && viewOrder.getOrderItems().size()>0){
				SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
				Session mSession = mSessionFactory.openSession();
				Transaction tx = mSession.beginTransaction();
				Order order = new Order();
				String orderNumber = System.currentTimeMillis()+ String.valueOf(viewOrder.getUid());
				Set<Orderitem> mOrderitems = new HashSet<>();
				for (ViewOrder.OrderItem vOrderItem : viewOrder.getOrderItems()) {
					Orderitem mOrderitem = new Orderitem();
					mOrderitem.setPcount(vOrderItem.getPcount());
					mOrderitem.setPname(vOrderItem.getPname());
					Product p = new Product();
					p.setPid(vOrderItem.getProduct());
					mOrderitem.setProduct(p);
					mOrderitem.setProductpic(vOrderItem.getProductpic());
					mOrderitem.setProductprice(vOrderItem.getProductprice());
//					mOrderitem.setRemarks(vOrderItem.getRemarks());					
					mOrderitem.setOrdernumber(orderNumber);
					mOrderitem.setOrder(order);
					mSession.save(mOrderitem);
					mOrderitems.add(mOrderitem);
				}
				order.setOrdernumber(orderNumber);
				order.setOrdertime(new Date(System.currentTimeMillis()));
//				order.setPaypic(viewOrder.getPayicon());  周靖说需求不要传，那就不传  
				User user = new User();
				//22000桶限制
				user.setUserid(viewOrder.getUid());
				order.setUser(user);
				order.setStatue(0);
				order.setPcount(viewOrder.getTotalPrice());
				order.setOrderitems(mOrderitems);
				Serializable result = mSession.save(order);
//				mSession.flush();
				tx.commit();
				
				count = (Long) result;
				System.out.println("插入订单数量："+count);
				mSession.close();
//				mSessionFactory.close();
				return count;
			}else{
				return count;
			}
		}
		/***
		 * 查自己的订单
		 * @param uid
		 * @param statue
		 */
		public List<ViewOrder> getOrdersByUserId(Long uid,int statue){
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();
			Transaction tx = mSession.beginTransaction();
			try {
				@SuppressWarnings("unchecked")
				List<User>users = mSession.createQuery("from com.jm.entity.User u where u.userid=:uid").setParameter("uid", uid).list();
				List<ViewOrder>orders = new ArrayList<>();
				if (users!=null && users.size()>0) {
					User user = users.get(0);
					Set<Order>mOrders = user.getOrders();
					for (Order order : mOrders) {
						if(order.getStatue()==statue){
							ViewOrder mOrder = new ViewOrder();						
							mOrder.setUid(user.getUserid());
							mOrder.setOrderNumber(order.getOrdernumber());
							if (order.getPcount()!=null )
								mOrder.setTotalPrice(order.getPcount());
							else
								mOrder.setTotalPrice(-1);  //总价为空，但是有订单，说明计算有误
							mOrder.setStatue(order.getStatue());
							mOrder.setOrderTime(order.getOrdertime());
							mOrder.setPayicon(order.getPaypic());
							mOrder.setUserName(user.getName());
							
							List<OrderItem>VOrderItems = new ArrayList<>();
							Set<Orderitem>mOrderitems = order.getOrderitems();
							for (Orderitem orderitem : mOrderitems) {
								OrderItem mVOrderItem = mOrder.new OrderItem();
								mVOrderItem.setAddress(orderitem.getAddress());
								mVOrderItem.setOrderByOrdernumber(orderitem.getOrdernumber());
								mVOrderItem.setPid(orderitem.getProduct().getPid());
								mVOrderItem.setPname(orderitem.getPname());
								mVOrderItem.setProductpic(orderitem.getProduct().getPicurl());
								mVOrderItem.setPcount(orderitem.getPcount());
								mVOrderItem.setProductprice(orderitem.getProductprice());
								VOrderItems.add(mVOrderItem);
							}
							mOrder.setOrderItems(VOrderItems);
							mOrder.setOrderid(order.getId());
							orders.add(mOrder);
							
						}else
						{
							
						}
					}
				}
				mSession.flush();
				
				if (orders.size()>0){
					java.util.Collections.sort(orders, new Comparator<ViewOrder>() {

						@Override
						public int compare(ViewOrder o1, ViewOrder o2) {
							// TODO Auto-generated method stub
							int ret = o2.getOrderTime().compareTo(o1.getOrderTime());
								
							return ret;
						}
					});
				}
				return orders;
			} finally {
				mSession.close();
//				mSessionFactory.close();
			}
			
		}
		
		/***
		 * 查下级订单
		 * @param uid
		 * @param statue
		 */
		public List<ViewOrder> getDownOrders(Long uid,int statue){
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();
			Transaction tx = mSession.beginTransaction();
			try {
				@SuppressWarnings("unchecked")			
				List<User>users = mSession.createQuery("from com.jm.entity.User u where u.authorizedpersonid=:uid").setParameter("uid", uid).list();
				List<ViewOrder>orders = new ArrayList<>();
				if (users!=null && users.size()>0) {
					for (User user : users) {
						Set<Order>mOrders = user.getOrders();
						for (Order order : mOrders) {
							if(order.getStatue()==statue){
								ViewOrder mOrder = new ViewOrder();	
								mOrder.setUid(user.getUserid());
								mOrder.setOrderNumber(order.getOrdernumber());
								if (order.getPcount()!=null )
								mOrder.setTotalPrice(order.getPcount());
								else
								mOrder.setTotalPrice(-1);  //总价为空，但是有订单，说明计算有误
								mOrder.setStatue(order.getStatue());
								mOrder.setOrderTime(order.getOrdertime());
								mOrder.setUserName(user.getName());
								List<OrderItem>VOrderItems = new ArrayList<>();
								Set<Orderitem>mOrderitems = order.getOrderitems();
								for (Orderitem orderitem : mOrderitems) {
									OrderItem mVOrderItem = mOrder.new OrderItem();
									mVOrderItem.setAddress(orderitem.getAddress());
									mVOrderItem.setOrderByOrdernumber(orderitem.getOrdernumber());
									mVOrderItem.setPid(orderitem.getProduct().getPid());
									mVOrderItem.setPname(orderitem.getPname());
									mVOrderItem.setProductpic(orderitem.getProduct().getPicurl());
									mVOrderItem.setPcount(orderitem.getPcount());
									mVOrderItem.setProductprice(orderitem.getProductprice());
									VOrderItems.add(mVOrderItem);
								}
								mOrder.setOrderItems(VOrderItems);
								mOrder.setOrderid(order.getId());
								orders.add(mOrder);
							}else
							{
								
							}
						}
					}
					
				}
				
				if (orders.size()>0) {
					java.util.Collections.sort(orders, new Comparator<ViewOrder>() {

						@Override
						public int compare(ViewOrder o1, ViewOrder o2) {
							// TODO Auto-generated method stub
							int ret = o2.getOrderTime().compareTo(o1.getOrderTime());
							return ret;
						}
					});
				}
				return orders;
			} finally {
				mSession.flush();
				mSession.close();
//				mSessionFactory.close();
			}
			
		}
		
		
		
		public int getOrderUserCanUpgradeCount(int typeid){
			int levelCount = -1;
			switch (typeid) {
			case 2:
				levelCount = EnumAgentUpgrade.ZONG_DAI.getUpCount();
				break;
			case 3:
				levelCount = EnumAgentUpgrade.AGENT_LEVEL_1.getUpCount();
				break;
			case 4:
				levelCount = EnumAgentUpgrade.AGENT_LEVEL_2.getUpCount();
				break;
			case 5:
				levelCount = EnumAgentUpgrade.TEYUE_DAI.getUpCount();
				break;
			default:
				break;
			}
			return levelCount;
		}
		
		
		public int canUpGrade(int ordersBuckets){
			if(ordersBuckets>= EnumAgentUpgrade.ZONG_DAI.getUpCount()){
				return 2;
			}else if (ordersBuckets>=EnumAgentUpgrade.AGENT_LEVEL_1.getUpCount()) {
				return 3;
			}else if (ordersBuckets>=EnumAgentUpgrade.AGENT_LEVEL_2.getUpCount()){
				return 4;
			}else if (ordersBuckets>=EnumAgentUpgrade.TEYUE_DAI.getUpCount()){
				return 5;
			}else {
				return -1;
			}
		}
		
		/**
		 * 确认订单
		 * 1.下普通订单
		 * 2.一次下的订单量可以升级为更高级代理
		 * 特约代理   8桶  
		 * 二级代理 48桶  
		 * 一级代理 200桶  
		 * 说明：有且只有当一种货品的数量一次购买量大于规定量才会有升级
		 * @param orderid
		 * @return
		 */
		@SuppressWarnings("deprecation")
		public synchronized boolean confirmOrder(Long orderid){
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();
			Transaction tx = mSession.beginTransaction();
			boolean result = false;
			try {
				@SuppressWarnings("unchecked")
				List<Order>orders = mSession.createQuery("from com.jm.entity.Order o where o.id=:oid").setParameter("oid", orderid).list();
				if(orders!=null && orders.size()>0){
					Order order = orders.get(0);
					order.setStatue(1);
					
					User user = order.getUser();
					Long upuid = user.getAuthorizedpersonid();
					if(getOrderUserCanUpgradeCount(user.getAgenttype().getTypeid())>0){
//						user.setCanupgradelevel(0);
					}
					Set<Orderitem>orderItems = order.getOrderitems();
					@SuppressWarnings("unchecked")
					List<User>upUser = mSession.createQuery("from com.jm.entity.User u where u.userid=:uid").setParameter("uid", upuid).list();
					if(upUser!=null && upUser.size()>0){
						User aUser = upUser.get(0);
						if(aUser.getUserid()==1){
							//订单用户增加相应的库存
							@SuppressWarnings("unchecked")
							List<User>orderUser = mSession.createQuery("from com.jm.entity.User u where u.userid=:uid").setParameter("uid", order.getUser().getUserid()).list();							
							if(orderUser!=null && orderUser.size()>0){
								User aOUser = orderUser.get(0);
								int isUpgradeCount = aOUser.getAgenttype().getBukets();

								@SuppressWarnings("unchecked")
								Set<Userstock>userstocks = aOUser.getUserstocks();
								System.out.println(userstocks.size());
								double totalAreaCount = 0d;
								if(userstocks!=null && userstocks.size()>0){
										for ( Orderitem orderitem : orderItems) {
											int count = 0;
											for (Userstock userstock : userstocks) {
												count+=1;
												if(userstock.getProduct().getPid()==orderitem.getProduct().getPid()){
													Double stocks = userstock.getTotalstock();
													int saleCounts = orderitem.getPcount();
													if(aOUser.getAgenttype().getTypeid()>2){
														int targetAgentId = canUpGrade(saleCounts);
														if(targetAgentId!= -1){
															aOUser.setCanupgradelevel(targetAgentId);
															aOUser.setExaminelevelstatue(0);
														}
													}
													Double subStocks = stocks + saleCounts;
													totalAreaCount +=saleCounts;
													userstock.setTotalstock(subStocks);
													mSession.createSQLQuery("update userstock set totalstock=:total where id=:id").setParameter("total", subStocks).setParameter("id", userstock.getId()).executeUpdate();
													break;
												}
													//该商品为第一次备货,库存除pid，totalstock其他同其他记录
													if(count == userstocks.size()){
														Userstock mUserstock = new Userstock();
														mUserstock.setAgenttype(userstock.getAgenttype());
														mUserstock.setUser(userstock.getUser());
														mUserstock.setTypename(userstock.getTypename());
														int saleCounts = orderitem.getPcount(); //只针对一种品类产品，如果有多个种类产品，不计算总数
														if(aOUser.getAgenttype().getTypeid()>2){
															int targetAgentId = canUpGrade(saleCounts);
															if(targetAgentId!= -1){
																aOUser.setCanupgradelevel(targetAgentId);
																aOUser.setExaminelevelstatue(0);
															}
														}
														mUserstock.setProduct(orderitem.getProduct());
														mUserstock.setTotalstock(Double.valueOf(saleCounts));
														totalAreaCount +=saleCounts;
														mSession.createSQLQuery("update userstock set totalstock=:total where id=:id").setParameter("total", saleCounts).setParameter("id", userstock.getId()).executeUpdate();
													}
											}
										}
										int a = (int)totalAreaCount;
										aOUser.getArea().setAllbuckets(aOUser.getArea().getAllbuckets()+a);//增加该区域的货品数量，目前不分货品种类
										mSession.createSQLQuery("update area set allbuckets=:counts where areaid=:id").setParameter("counts",(aOUser.getArea().getAllbuckets()+a)).setParameter("id", aOUser.getArea().getAreaid()).executeUpdate();
								}else{
									//该用户没有库存  这种情况在上线后只会出现一次  因为新增一个新用户时，就会生成一个库存，此时用户是没有库存的，之后都会有库存记录
									for (Orderitem orderitem : orderItems) {
										Userstock mUserstock = new Userstock();
										mUserstock.setUser(order.getUser());
										mUserstock.setProduct(orderitem.getProduct());
										mUserstock.setAgenttype(aOUser.getAgenttype());
										mUserstock.setTypename(aOUser.getAgenttype().getTypename());
										int saleCounts = orderitem.getPcount();
//										if (isUpgradeCount>0 && isUpgradeCount <= saleCounts){
//											aOUser.setCanupgradelevel(aOUser.getAgenttype().getTypeid()-1);
//										}
										//第一次进货是在第一次申请成为代理的时候，此时生成多大的下级代理就会有多少库存的增加，不会在第一次就需要计算升级到多少级
										if(aOUser.getAgenttype().getTypeid()>2){
											int targetAgentId = canUpGrade(saleCounts);
											if(targetAgentId!= -1){
												aOUser.setCanupgradelevel(targetAgentId);
												aOUser.setExaminelevelstatue(0);
											}
										}
										mUserstock.setProduct(orderitem.getProduct());
										mUserstock.setTotalstock(Double.valueOf(saleCounts));
										totalAreaCount +=saleCounts;										
										mSession.createSQLQuery("insert into userstock (userid,pid,typeid,typename,totalstock) values (:uid,:pid,:tid,:tname,:totals) ").setParameter("uid",order.getUser().getUserid())
										.setParameter("pid",orderitem.getProduct().getPid()).setParameter("tid",aOUser.getAgenttype().getTypeid()).setParameter("tname",aOUser.getAgenttype().getTypename()).setParameter("totals",Double.valueOf(saleCounts)).executeUpdate();
									}
									int a = (int)totalAreaCount;
									aOUser.getArea().setAllbuckets(aOUser.getArea().getAllbuckets()+a);//增加该区域的货品数量，目前不分货品种类
									mSession.createSQLQuery("update area set allbuckets=:counts where areaid=:id").setParameter("counts",(aOUser.getArea().getAllbuckets()+a)).setParameter("id", aOUser.getArea().getAreaid()).executeUpdate();
								}
//								mSession.saveOrUpdate(aOUser);
							}else{
								result = false;
							}
						}else{
							/*String realPath = ServletActionContext.getServletContext().getRealPath("upload/log");			    
						    String picPath = "";
							String picName = String.valueOf(System.currentTimeMillis()+".txt");
				        	picPath =  "upload/product/"+picName;
				        	File savefile = new File(new File(realPath),picName);
					        PrintStream ps = new PrintStream(new FileOutputStream(savefile));*/
							
							@SuppressWarnings("unchecked")						
							Set<Userstock>userstocks = aUser.getUserstocks();
							System.out.println(userstocks.size());
							if(userstocks!=null && userstocks.size()>0){
									for (Userstock userstock : userstocks) {
										for (Orderitem orderitem : orderItems) {
											if(userstock.getProduct().getPid()==orderitem.getProduct().getPid()){
												Double stocks = userstock.getTotalstock();
//												System.out.println("总数："+stocks);
//												ps.append("总数："+stocks+"\n");
												int saleCounts = orderitem.getPcount();
//												System.out.println("下单数量："+saleCounts);
//												ps.append("下单数量："+saleCounts+"\n");
												Double subStocks = stocks - saleCounts;
												if(subStocks<0) return false;
//												System.out.println("剩余数量："+subStocks);
//												ps.append("剩余数量："+subStocks+"\n");
												userstock.setTotalstock(subStocks);
//												System.out.println("更新后总数："+userstock.getTotalstock());
//												mSession.saveOrUpdate(userstock);
												mSession.createSQLQuery("update userstock set totalstock=:total where id=:id").setParameter("total", subStocks).setParameter("id", userstock.getId()).executeUpdate();
//												ps.append("更新后库存数量："+userstock.getTotalstock()+"\n");
											}
										}						
									}
								}else{
									return false;
								}
//									mSession.saveOrUpdate(aUser);
									//订单用户增加相应的库存
//									ps.append(" 下单用户uid"+order.getUser().getUserid());
									@SuppressWarnings("unchecked")
									List<User>orderUser = mSession.createQuery("from com.jm.entity.User u where u.userid=:uid").setParameter("uid", order.getUser().getUserid()).list();
									
									if(orderUser!=null && orderUser.size()>0){
										User aOUser = orderUser.get(0);
//										ps.append("查询后订单用户id："+aOUser.getUserid()+aOUser.getName()+"\n");
										System.out.println(aOUser.getUserid());
										int isUpgradeCount = aOUser.getAgenttype().getBukets();
										@SuppressWarnings("unchecked")
										Set<Userstock>userOstocks = aOUser.getUserstocks();
										double totalAreaCount = 0d;
										if(userOstocks!=null && userOstocks.size()>0){
											for ( Orderitem orderitem : orderItems) {
												int count = 0;
												for (Userstock userstock : userOstocks) {
													count+=1;
//													ps.append("订单用户现有库存产品id："+userstock.getProduct().getPid()+"\n");
													if(userstock.getProduct().getPid()==orderitem.getProduct().getPid()){
														Double stocks = userstock.getTotalstock();
//														ps.append("订单用户现有库存："+stocks+"\n");
//														ps.append("订单用户现有库存用户id："+userstock.getUser().getUserid()+"\n");
//														ps.append("订单用户现有库存id："+userstock.getId()+"\n");
														int saleCounts = orderitem.getPcount();
														if(aOUser.getAgenttype().getTypeid()>2){
															int targetAgentId = canUpGrade(saleCounts);
															if(targetAgentId!= -1){
																aOUser.setCanupgradelevel(targetAgentId);
																aOUser.setExaminelevelstatue(0);
															}
														}
														Double subStocks = stocks + saleCounts;
														totalAreaCount +=saleCounts;
														userstock.setTotalstock(subStocks);
//														ps.append("新增库存："+subStocks+"\n");
														mSession.createSQLQuery("update userstock set totalstock=:total where id=:id").setParameter("total", subStocks).setParameter("id", userstock.getId()).executeUpdate();
														break;
													}
														//该商品为第一次备货,库存除pid，totalstock其他同其他记录
														if(count == userOstocks.size()){
//															ps.append("订单用户第一次增加库存："+count+"\n");
															Userstock mUserstock = new Userstock();
															mUserstock.setAgenttype(userstock.getAgenttype());
															mUserstock.setUser(userstock.getUser());
															mUserstock.setTypename(userstock.getTypename());
															int saleCounts = orderitem.getPcount(); //只针对一种品类产品，如果有多个种类产品，不计算总数
															if(aOUser.getAgenttype().getTypeid()>2){
																int targetAgentId = canUpGrade(saleCounts);
																if(targetAgentId!= -1){
																	aOUser.setCanupgradelevel(targetAgentId);
																	aOUser.setExaminelevelstatue(0);
																}
															}
															mUserstock.setProduct(orderitem.getProduct());
															mUserstock.setTotalstock(Double.valueOf(saleCounts));
															totalAreaCount +=saleCounts;
															mSession.createSQLQuery("update userstock set totalstock=:total where id=:id").setParameter("total", saleCounts).setParameter("id", userstock.getId()).executeUpdate();
														}
													
												}
											}
											
											
											int a = (int)totalAreaCount;
											aOUser.getArea().setAllbuckets(aOUser.getArea().getAllbuckets()+a);//增加该区域的货品数量，目前不分货品种类
											mSession.createSQLQuery("update area set allbuckets=:counts where areaid=:id").setParameter("counts",(aOUser.getArea().getAllbuckets()+a)).setParameter("id", aOUser.getArea().getAreaid()).executeUpdate();
												
										}else{
											//该用户没有库存  这种情况在上线后只会出现一次  因为新增一个新用户时，就会生成一个库存，此时用户是没有库存的，之后都会有库存记录
											for (Orderitem orderitem : orderItems) {
												Userstock mUserstock = new Userstock();
												mUserstock.setUser(order.getUser());
												mUserstock.setProduct(orderitem.getProduct());
												mUserstock.setAgenttype(aOUser.getAgenttype());
												mUserstock.setTypename(aOUser.getAgenttype().getTypename());
												int saleCounts = orderitem.getPcount();
												if(aOUser.getAgenttype().getTypeid()>2){
													int targetAgentId = canUpGrade(saleCounts);
													if(targetAgentId!= -1){
														aOUser.setCanupgradelevel(targetAgentId);
														aOUser.setExaminelevelstatue(0);
													}
												}
												mUserstock.setProduct(orderitem.getProduct());
												mUserstock.setTotalstock(Double.valueOf(saleCounts));
												totalAreaCount+=saleCounts;
//												mSession.save(mUserstock);
												mSession.createSQLQuery("insert into userstock (userid,pid,typeid,typename,totalstock) values (:uid,:pid,:tid,:tname,:totals) ").setParameter("uid",order.getUser().getUserid())
												.setParameter("pid",orderitem.getProduct().getPid()).setParameter("tid",aOUser.getAgenttype().getTypeid()).setParameter("tname",aOUser.getAgenttype().getTypename()).setParameter("totals",Double.valueOf(saleCounts)).executeUpdate();
											}
											int a = (int)totalAreaCount;
											aOUser.getArea().setAllbuckets(aOUser.getArea().getAllbuckets()+a);//增加该区域的货品数量，目前不分货品种类
											mSession.createSQLQuery("update area set allbuckets=:counts where areaid=:id").setParameter("counts",(aOUser.getArea().getAllbuckets()+a)).setParameter("id", aOUser.getArea().getAreaid()).executeUpdate();
											
										}
//										mSession.saveOrUpdate(aOUser);
										
									}else{
										result = false;
									}
							}
						
					}else{
						result = false;
					}
					
					mSession.saveOrUpdate(order);
					result = true;
				}else{
					result = false;
				}
				tx.commit();
			} catch (Exception e) {
				// TODO: handle exception
				result = false;
//				tx.rollback();
			}finally {
				mSession.close();
//				mSessionFactory.close();
			}
			return result;
			
			
		}


		public int addArea(String areaName,long createUid){
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();
			Transaction tx = mSession.beginTransaction();
			String hql = "from com.jm.entity.Area a where a.areaname=:aname and a.createuid=:cuid ";
			@SuppressWarnings("unchecked")
			List<Area>areas = mSession.createQuery(hql).setParameter("aname", areaName).setParameter("cuid", createUid).list();
			if (areas!=null && areas.size()>0) {
				return 2;
			}
			Area mArea = new Area();
			mArea.setAllbuckets(0);
			mArea.setPopularity(0);
			mArea.setAreaname(areaName);
			mArea.setCreateuid(createUid);
			Serializable result = mSession.save(mArea);
			System.out.println(result);
			
			tx.commit();
			mSession.close();
//			mSessionFactory.close();
			if(result!=null){
				return 0;
			}else{
				return 1;
			}
			
		}
		
		public List<ViewArea> getAreaByUid(long uid){
			List<ViewArea>areas = new ArrayList<>();
			SessionFactory mSessionFactory = SessionFactoryManager.getInstance();;
			Session mSession = mSessionFactory.openSession();
			String sql = "from com.jm.entity.Area area where area.createuid =:uid";
			@SuppressWarnings("unchecked")
			List<Area>mAreas = mSession.createQuery(sql).setParameter("uid", uid).list();
			if(mAreas!=null && mAreas.size()>0){
				for (Area area : mAreas) {
					ViewArea vArea = new ViewArea();
					vArea.setAreaid(area.getAreaid());
					vArea.setAllbuckets(area.getAllbuckets());
					vArea.setAreaname(area.getAreaname());
					vArea.setPopularity(area.getPopularity());
					areas.add(vArea);
				}
			}
			mSession.close();
//			mSessionFactory.close();
			return areas;
		}

}
